package controller;

import java.util.Date;

import model.CapDo;
import model.NguoiDung;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Radiogroup;
import org.zkoss.zul.Textbox;

import dao.entity.CapDoDAO;
import dao.entity.NguoiDungDAO;

@SuppressWarnings("serial")
public class Register extends SelectorComposer<Component> {
	@Wire
	private Textbox email;
	@Wire
	private Textbox hoTen;
	@Wire
	private Textbox password;
	@Wire
	private Textbox re_password;
	@Wire
	private Datebox ngaySinh;
	@Wire
	private Radiogroup gioiTinh;
	@Wire
	private Textbox diaChi;
	@Wire
	private Textbox soDienThoai;

	@Listen("onClick=#submitButton")
	public void saveRegister() {
		boolean gioiTinhNguoiDung = false;
		System.out.println("Email: " + email.getValue());
		System.out.println("Họ tên: " + hoTen.getValue());
		System.out.println("Mật khẩu: " + password.getValue());
		System.out.println("Nhập lại mật khẩu: " + re_password.getValue());
		System.out.println("Ngày sinh: " + ngaySinh);
		System.out.println("Giới tính 1: "
				+ gioiTinh.getItemAtIndex(0).isChecked());
		System.out.println("Giới tính 2: "
				+ gioiTinh.getItemAtIndex(1).isChecked());
		System.out.println("Địa chỉ: " + diaChi.getValue());
		System.out.println("Số điệnt thoại: " + soDienThoai.getValue());
		if (gioiTinh.getItems().get(0).isChecked()) {
			gioiTinhNguoiDung = true;
		} else {
			gioiTinhNguoiDung = false;
		}
		String tenNguoiDung = hoTen.getValue();
		String email_nguoiDung = email.getValue();
		String pass = password.getValue();
		Date ngaySinhNguoiDung = ngaySinh.getValue();
		String diaChiNguoiDung = diaChi.getValue();
		String sdtNguoiDung = soDienThoai.getValue();
		boolean isExist = NguoiDungDAO.checkUser(email.getValue());
		if (!password.getValue().equals(re_password.getValue())) {
			throw new WrongValueException(re_password, "Pass nhập lại sai nhé");
		}

		if (isExist) {
			throw new WrongValueException(email,
					"Email này có người dùng rồi nhé");
		} else {
			CapDoDAO capDoDAO = new CapDoDAO();
			CapDo capDo = capDoDAO.findByID(1);
			NguoiDung nguoiDung = new NguoiDung(tenNguoiDung, email_nguoiDung,
					SHA1.getSHA1(pass), gioiTinhNguoiDung, diaChiNguoiDung,
					sdtNguoiDung, ngaySinhNguoiDung, capDo);
			NguoiDungDAO nguoiDungDAO = new NguoiDungDAO();
			nguoiDungDAO.persist(nguoiDung);
			Sessions.getCurrent().setAttribute("email", email_nguoiDung);
			Executions.sendRedirect("customer.zul?target=success");
		}
	}
}
